package SecondeStage.Networkprogramming.Socket;

import FirstStage.DuoTai.B;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Tcp02Server {
    public static void main(String[] args) throws IOException {
        // 1. 在本机的9999端口监听，等待连接(要求9999端口没有其他服务在监听9999)
        ServerSocket serverSocket = new ServerSocket(9999);
        // 2. 当没有客户端连接9999端口时，程序会阻塞，等待连接
        // 如果有客户端连接，则会返回Socket对象，程序继续
        Socket socket = serverSocket.accept();
        System.out.println("socket = " + socket.getClass());
        // 3. 通过socket.getInputStream() 读取客户端写入到数据通道的数据，显示
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(inputStream));
        // 4. IO读取,使用字符流
        String s=bufferedReader.readLine();
        System.out.println(s);
        // 5. 获取socket相关联的输出流
        OutputStream outputStream =socket.getOutputStream();
        BufferedWriter bufferedWriter =new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("hello,client 字符流");
        bufferedWriter.newLine();
        bufferedWriter.flush();
        // 6.关闭流和socket
        bufferedReader.close();
        bufferedWriter.close();
        socket.close();
        serverSocket.close();
    }
}
